package com.hxqc.basic.interceptor;

import java.lang.reflect.Method;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.hxqc.basic.common.Constants;
import com.hxqc.basic.serivce.CommonService;

import net.sf.json.JSONArray;

@Component
@Aspect
public class LogInterceptor {

	@Resource
	private CommonService commonService;

	/**
	 * 记录操作日志
	 * 
	 * @param point
	 * @throws Exception
	 */

	@AfterReturning(value = "execution(public * com.hxqc.basic.serivce..*.*(..)) && @annotation(com.hxqc.basic.interceptor.LogAnnotation)")
	public void record(JoinPoint point) throws Exception {
		LogAnnotation log = getAnnotation(point);
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		if (null == request)
			return;
		HttpSession session = request.getSession();
		if (null == session.getAttribute(Constants.USER_SESSION_KEY))
			return;
		@SuppressWarnings("unchecked")
		Map<String, Object> user = (Map<String, Object>) session.getAttribute(Constants.USER_SESSION_KEY);
		user.put("logvalue", log.value());
		user.put("signature", point.getSignature().toString());
		user.put("args", JSONArray.fromObject(point.getArgs()).toString());
		commonService.insertOptionLog(user);
	}

	/**
	 * 获得注释内容
	 * 
	 * @param joinPoint
	 * @return
	 */
	private static LogAnnotation getAnnotation(JoinPoint joinPoint) {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();
		if (method != null) {
			return method.getAnnotation(LogAnnotation.class);
		}
		return null;
	}

}
